/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package InterfaceCliente;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import pbl_cliente.*;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author tayane
 */
public class JanelaChat extends javax.swing.JFrame implements Observer {

    /**
     * Creates new form JanelaChat
     */
    //private ConexaoUDP conexao;
    
    private CotaChat chat;
    private DataOutputStream msgEnviada;
    private PBL_cliente cli;
    
    public JanelaChat(CotaChat chat, PBL_cliente cli) {
        super("Chat - Agenda Eletronica");
        this.cli = cli;
        initComponents();
        setVisible(true);
        setLocationRelativeTo(null);
        this.chat = chat;
        chat.addObserver(this);
        //escreve("Chat iniciado com " + meuSocket.getInetAddress().getHostAddress());
        mensagemjTextArea.requestFocusInWindow();
    }

    private JanelaChat() {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    
    private void envia() throws SocketException, UnknownHostException, IOException {      
        if (!mensagemjTextArea.getText().isEmpty()) {
               chat.enviaMsgMulticast(mensagemjTextArea.getText());
               mensagemjTextArea.setText("");
        }
    }
    
    public void escreve(String texto){
        chatjTextArea.append(texto + "\n");
         if (!chatjTextArea.getText().isEmpty() && !chatjTextArea.isFocusOwner()) {
              chatjTextArea.setCaretPosition(chatjTextArea.getText().length() - 1);
         }      
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        mensagemjTextArea = new javax.swing.JTextArea();
        enviarjButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        chatjTextArea = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        mensagemjTextArea.setColumns(20);
        mensagemjTextArea.setRows(5);
        mensagemjTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                mensagemjTextAreaKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(mensagemjTextArea);

        enviarjButton1.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N
        enviarjButton1.setText("ENVIAR");
        enviarjButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enviarjButton1ActionPerformed(evt);
            }
        });
        enviarjButton1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                enviarjButton1KeyReleased(evt);
            }
        });

        chatjTextArea.setColumns(20);
        chatjTextArea.setRows(5);
        jScrollPane2.setViewportView(chatjTextArea);

        jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
        jLabel1.setText("CHAT - AGENDA ELETRÔNICA");

        jButton1.setText("Enviar Arquivo");

        jButton2.setText("Emoticons");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1)
                                .addGap(84, 84, 84)
                                .addComponent(jButton2))
                            .addComponent(jScrollPane1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(enviarjButton1)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(107, 107, 107))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jLabel1)
                .addGap(16, 16, 16)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(enviarjButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void enviarjButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enviarjButton1ActionPerformed
        try {
            envia();
        } catch (SocketException ex) {
            Logger.getLogger(JanelaChat.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnknownHostException ex) {
            Logger.getLogger(JanelaChat.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JanelaChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_enviarjButton1ActionPerformed

    private void enviarjButton1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_enviarjButton1KeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_enviarjButton1KeyReleased

    private void mensagemjTextAreaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mensagemjTextAreaKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            try {
                envia();
            } catch (SocketException ex) {
                Logger.getLogger(JanelaChat.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnknownHostException ex) {
                Logger.getLogger(JanelaChat.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(JanelaChat.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_mensagemjTextAreaKeyReleased

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        chat.enviaAvisoFecheiJanela();
        cli.incContChat();
    }//GEN-LAST:event_formWindowClosed

    @Override
    public void update(Observable o, Object o1) {
        escreve(chat.getMensagem());
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JanelaChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JanelaChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JanelaChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JanelaChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JanelaChat().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea chatjTextArea;
    private javax.swing.JButton enviarjButton1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea mensagemjTextArea;
    // End of variables declaration//GEN-END:variables

}
